<?php

// +----------------------------------------------------------------------
// | MC PHP[基于ThinkPHP6.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://www.mingchangruanjian.com
// +----------------------------------------------------------------------
// | Author jokerfei [ jokerfei377@gmail.com ]
// +----------------------------------------------------------------------
// | 铭畅软件 技术部 出品
// +----------------------------------------------------------------------

namespace app\api\controller\v1;

use app\api\controller\Base;
use app\common\service\ApiReturn;
use think\facade\Db;
use app\admin\model\user\User;
use app\admin\model\user\Assets as AssetsModel;
use app\admin\model\user\UserWithdraw as UserWithdrawModel;
use app\admin\model\user\UserWithdrawAccount as UserWithdrawAccountModel;
/**
 * 会员提现
 */
class Withdraw extends Base
{

    /**
     * @Author: Bryant
     * @Date: 2023-06-13 14:15:58
     * @method post
     * @title 绑定提现账号
     */
    public function bindWithdrawAccount($data=[], $user=[])
    {
        $data['user_id'] = $user['id'];
        $info = UserWithdrawAccountModel::where('user_id', $user['id'])->where('account_type', $data['account_type'])->find();
        // 启动事务
        Db::startTrans();
        try {
            if ($info) {
                $res1 = UserWithdrawAccountModel::where(['user_id' => $user['id']])->update(['is_default' => 0, 'update_time' => time()]);
                $data['update_time'] = time();
                $res = UserWithdrawAccountModel::where('user_id', $user['id'])->where('account_type', $data['account_type'])->update($data);
                if ($res == false || $res1 == false) {
                    throw new \Exception('绑定失败');
                }
            } else {
                $data['status'] = 1;
                $res = UserWithdrawAccountModel::create($data);
                if (!$res) {
                    throw new \Exception('绑定失败');
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ApiReturn::r(0, null, $e->getMessage());
        }
        $info = UserWithdrawAccountModel::where('user_id', $user['id'])->where('account_type', $data['account_type'])->find();
        return ApiReturn::r(1, $info, '绑定成功');
    }

    /**
     * @Author: Bryant
     * @Date: 2023-06-13 14:26:59
     * @method post
     * @title 获取绑定的提现账号
     */
    public function getWithdrawAccount($data, $user)
    {
        $accountTypes = UserWithdrawAccountModel::SELECT_LIST_ACCOUNT_TYPE;
        $binds = [];
        foreach ($accountTypes as $type => $item) {
            $exists = UserWithdrawAccountModel::where('user_id', $user['id'])->where('account_type', $type)->find();
            $is_bind = $exists ? 1 : 0;
            $binds[] = ['account_type' => $type, 'is_bind' => $is_bind];
        }
        return ApiReturn::r(1, $binds, '请求成功');
    }
    /**
     * @Author: Bryant
     * @Date: 2023-06-13 14:33:24
     * @method post
     * @title 申请提现
     */
    public function withdraw($data = [], $user = [])
    {
        $money = $data['money'];
        $type = $data['account_type'];
        $pay_password = User::where('id', $user['id'])->value('pay_password');
        if (empty($pay_password)) {
            return ApiReturn::r(1001, null, '请设置支付密码');
        }
        if(password($data['pay_password']) != $pay_password){
            return ApiReturn::r(0, null, '支付密码不正确');
        }
        $withdrawConfig = sysconfig('user');
        // 启动事务
        Db::startTrans();
        try {
            $now_money = AssetsModel::where('user_id',$user['id'])->value('user_money');
            $wd_min_money = $withdrawConfig['min_withdraw_money'];
            // 提现金额起提标准判断
            if ($now_money < $wd_min_money) {
                throw new \Exception('您的余额暂未达到提现标准');
            }
            // 提现金额最低标准判断
            if ($wd_min_money > $money) {
                throw new \Exception('提现金额最低为' . $wd_min_money . '元');
            }
            // 提现金额不能大于余额
            if ($money > $now_money) {
                throw new \Exception('余额不足，无法提现');
            }
            //组合用户提现信息
            $account = UserWithdrawAccountModel::where(['user_id' => $user['id'], 'account_type' => $type])->find();
            if(!$account){
                throw new \Exception('未绑定提现账号');
            }

            $order_no = get_order_sn('TX');
            //记录日志
            $moneyLogService = new \app\service\user\UserMoneyLog();
            $moneylog = $moneyLogService->changeMoney($user['id'], -$money, 4, '会员申请提现', $order_no);
            if (!$moneylog) {
                throw new \Exception('更改余额失败');
            }

            $withdraw_data = [
                'user_id' => $user['id'],
                'true_name' => $account['true_name'],
                'order_sn' => $order_no,
                'cash_fee' => $money,
                'check_status' => 0,
                'account_type' => $type,
                'account' => $account['account'],
                'qrcode' => $account['qrcode'],
                'bank_name' => $account['bank_name'],
                'bank_type' => $account['bank_type'],
            ];
            //精度计算手续费
            $charge_type = $withdrawConfig['charge_type'];
            $charge = $withdrawConfig['charge'];
            if ($charge_type == 0) {
                //固定金额手续费
                $withdraw_handling_fee = $charge;
            } else {
                //百分比手续费
                $withdraw_handling_fee = bcmul($money, $charge * 0.01, 2);
            }
            $withdraw_data['pay_fee'] = bcsub($money, $withdraw_handling_fee, 2);
            $withdraw_data['handling_fee'] = $withdraw_handling_fee;
            // 新增提现记录
            $withdraw = UserWithdrawModel::create($withdraw_data);
            if (!$withdraw) {
                throw new \Exception('创建提现记录失败');
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ApiReturn::r(0, null, $e->getMessage());
        }
        return ApiReturn::r(1, null, '申请提现成功');
    }

    /**
     * 获取提现记录
     * @param  [type] $data [description]
     * @param  [type] $user [description]
     * @return [type]       [description]
     */
    public function withdrawList($data, $user)
    {
        $where[] = ['user_id', '=', $user['id']];
        if($data['start_time']){
            $where[] = ['create_time','>',strtotime($data['start_time'].' 00:00:00')];
        }
        if($data['end_time']){
            $where[] = ['create_time','<',strtotime($data['end_time'].' 23:59:59')];
        }
        $list = UserWithdrawModel::where($where)->order('id', 'desc')->paginate();
        foreach ($list as &$item) {
            if ($item['cash_status'] == 1) {
                $item['check_status'] = 3;
            } elseif ($item['cash_status'] == 2) {
                $item['check_status'] = 4;
            }
        }
        unset($item);
        return ApiReturn::r(1, $list, lang('common.successful'));
    }
}